package com.tbvtc.agriculturalcreditchainserver2025.utils.voice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.UUID;

@Slf4j
@Component
public class VoiceFileUtil {
    @Value("${agri.chat.voice.storage-path}")
    private String storagePath;

    @Value("${agri.chat.voice.access-path}")
    private String accessPath;

    /**
     * 将Base64编码的音频数据转为WAV文件并存储
     *
     * @param originalFileName 原始文件名（用于保留扩展名）
     * @return 前端可访问的音频URL（如：/api/voice/20251107/uuid.wav）
     */
    public String saveBase64AsWav(String base64, String originalFileName) throws IOException {
        // 注意：方法参数名已改为audioBytes，明确它是原始音频字节
        String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        File dir = new File(storagePath + dateDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        byte[] fileBytes = Base64.getDecoder().decode(base64);
        String fileExt = originalFileName.contains(".")
                ? originalFileName.substring(originalFileName.lastIndexOf("."))
                : ".wav";
        String uniqueFileName = UUID.randomUUID() + fileExt;
        File wavFile = new File(dir, uniqueFileName);

        // 直接写入原始音频字节（无需Base64解码，因为输入不是Base64）
        try (FileOutputStream fos = new FileOutputStream(wavFile)) {
            fos.write(fileBytes); // 直接写原始字节
        }
        log.info("保存音频文件成功：{}", wavFile.getAbsolutePath());
        log.info("访问音频文件：{}", accessPath + dateDir + "/" + uniqueFileName);
        return accessPath + dateDir + "/" + uniqueFileName;
    }
}